// 测试二元信号量的线程互斥效果

#include <gtest/gtest.h>
#include <semaphore.h>
#include <thread>
#include <atomic>

std::binary_semaphore sem(1); // 二元信号量

void critical_section(std::atomic<int>& counter) {
    sem.acquire();  // 获取信号量
    int temp = counter.load();
    std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟工作
    counter.store(temp + 1);
    sem.release();  // 释放信号量
}

TEST(SemaphoreTest, BinarySemaphore) {
    std::atomic<int> counter(0);
    std::thread t1(critical_section, std::ref(counter));
    std::thread t2(critical_section, std::ref(counter));

    t1.join();
    t2.join();

    EXPECT_EQ(counter.load(), 2);
}